<template>
  <div class="story-library">
    <div class="container">
      <div class="library-header">
        <h1 class="page-title">故事库</h1>
        <p class="page-description">
          探索精彩的故事世界，发现你喜欢的创作
        </p>
      </div>

      <!-- Filters and Search -->
      <div class="library-controls">
        <div class="search-section">
          <div class="search-input-wrapper">
            <Search :size="20" />
            <input
              v-model="searchQuery"
              type="text"
              class="search-input"
              placeholder="搜索故事标题、作者或内容..."
            />
          </div>
        </div>

        <div class="filter-section">
          <div class="filter-group">
            <label class="filter-label">分类</label>
            <select v-model="selectedCategory" class="filter-select">
              <option value="">全部分类</option>
              <option 
                v-for="category in storiesStore.categories" 
                :key="category"
                :value="category"
              >
                {{ category }}
              </option>
            </select>
          </div>

          <div class="filter-group">
            <label class="filter-label">排序</label>
            <select v-model="sortBy" class="filter-select">
              <option value="latest">最新发布</option>
              <option value="popular">最受欢迎</option>
              <option value="views">浏览量</option>
              <option value="likes">点赞数</option>
            </select>
          </div>

          <div class="view-toggle">
            <button
              @click="viewMode = 'grid'"
              :class="{ active: viewMode === 'grid' }"
              class="view-btn"
            >
              <Grid :size="16" />
            </button>
            <button
              @click="viewMode = 'list'"
              :class="{ active: viewMode === 'list' }"
              class="view-btn"
            >
              <List :size="16" />
            </button>
          </div>
        </div>
      </div>

      <!-- Category Tabs -->
      <div class="category-tabs">
        <button
          @click="selectedCategory = ''"
          :class="{ active: selectedCategory === '' }"
          class="category-tab"
        >
          全部
        </button>
        <button
          v-for="category in storiesStore.categories"
          :key="category"
          @click="selectedCategory = category"
          :class="{ active: selectedCategory === category }"
          class="category-tab"
        >
          {{ category }}
        </button>
      </div>

      <!-- Stories Grid/List -->
      <div class="stories-container">
        <div v-if="filteredStories.length === 0" class="empty-state">
          <div class="empty-icon">
            <BookOpen :size="64" />
          </div>
          <h3>暂无故事</h3>
          <p>{{ searchQuery ? '没有找到匹配的故事' : '还没有发布的故事' }}</p>
          <router-link to="/generate" class="btn btn-primary">
            <PenTool :size="16" />
            开始创作
          </router-link>
        </div>

        <div 
          v-else
          :class="['stories-grid', `stories-${viewMode}`]"
        >
          <div
            v-for="story in paginatedStories"
            :key="story.id"
            class="story-item"
            @click="goToStory(story.id)"
          >
            <div class="story-card card">
              <div class="story-header">
                <div class="story-title-section">
                  <h3 class="story-title">{{ story.title }}</h3>
                  <span class="story-category">{{ story.category }}</span>
                </div>
                <div class="story-actions">
                  <button
                    @click.stop="toggleLike(story.id)"
                    :class="{ liked: isUserLiked(story.id), disabled: !authStore.isAuthenticated }"
                    class="action-btn like-btn"
                    :title="authStore.isAuthenticated ? '' : '请先登录后点赞'"
                  >
                    <Heart :size="16" :fill="isUserLiked(story.id) ? 'currentColor' : 'none'" />
                    <span>{{ isUserLiked(story.id) ? '已点赞' : '点赞' }}</span>
                  </button>
                  <button @click.stop="shareStory(story)" class="action-btn">
                    <Share2 :size="16" />
                  </button>
                </div>
              </div>

              <div class="story-content">
                <p class="story-excerpt">{{ getExcerpt(story.content) }}</p>
              </div>

              <div class="story-meta">
                <div class="story-author">
                  <Users :size="16" />
                  <span>{{ story.author_name || story.author }}</span>
                </div>
                <div class="story-stats">
                  <div class="stat">
                    <Eye :size="14" />
                    <span>{{ formatNumber(story.views) }}</span>
                  </div>
                  <div class="stat">
                    <Heart :size="14" />
                    <span>{{ story.likes || 0 }}</span>
                  </div>
                  <div class="stat">
                    <MessageCircle :size="14" />
                    <span>{{ story.comments_count || story.comments?.length || 0 }}</span>
                  </div>
                  <div class="stat">
                    <Clock :size="14" />
                    <span>{{ formatDate(story.published_at || story.publishedAt) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Pagination -->
        <div v-if="totalPages > 1" class="pagination">
          <button
            @click="currentPage = Math.max(1, currentPage - 1)"
            :disabled="currentPage === 1"
            class="pagination-btn"
          >
            <ChevronLeft :size="16" />
            上一页
          </button>

          <div class="pagination-numbers">
            <button
              v-for="page in visiblePages"
              :key="page"
              @click="currentPage = page"
              :class="{ active: currentPage === page }"
              class="pagination-number"
            >
              {{ page }}
            </button>
          </div>

          <button
            @click="currentPage = Math.min(totalPages, currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="pagination-btn"
          >
            下一页
            <ChevronRight :size="16" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStoriesStore } from '../stores/stories'
import { useAuthStore } from '../stores/auth'
import { useToast } from 'vue-toastification'
import { gsap } from 'gsap'
import {
  Search,
  Filter,
  Grid,
  List,
  BookOpen,
  PenTool,
  Heart,
  Share2,
  Users,
  Eye,
  MessageCircle,
  Clock,
  ChevronLeft,
  ChevronRight
} from 'lucide-vue-next'

const router = useRouter()
const storiesStore = useStoriesStore()
const authStore = useAuthStore()
const toast = useToast()

const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('latest')
const viewMode = ref('grid')
const currentPage = ref(1)
const itemsPerPage = 12

const likedStories = ref(new Set())

const filteredStories = computed(() => {
  let stories = [...storiesStore.stories.filter(story => story.status === 'published')]

  // Filter by search query
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    stories = stories.filter(story =>
      story.title.toLowerCase().includes(query) ||
      story.content.toLowerCase().includes(query) ||
      (story.author_name || story.author || '').toLowerCase().includes(query)
    )
  }

  // Filter by category
  if (selectedCategory.value) {
    stories = stories.filter(story => story.category === selectedCategory.value)
  }

  // Sort stories
  switch (sortBy.value) {
    case 'latest':
      stories.sort((a, b) => new Date(b.published_at || b.publishedAt) - new Date(a.published_at || a.publishedAt))
      break
    case 'popular':
      stories.sort((a, b) => (b.likes + b.views) - (a.likes + a.views))
      break
    case 'views':
      stories.sort((a, b) => b.views - a.views)
      break
    case 'likes':
      stories.sort((a, b) => b.likes - a.likes)
      break
  }

  return stories
})

const totalPages = computed(() => Math.ceil(filteredStories.value.length / itemsPerPage))

const paginatedStories = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage
  const end = start + itemsPerPage
  return filteredStories.value.slice(start, end)
})

const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  let end = Math.min(totalPages.value, start + maxVisible - 1)

  if (end - start + 1 < maxVisible) {
    start = Math.max(1, end - maxVisible + 1)
  }

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

const getExcerpt = (content) => {
  return content.length > 150 ? content.substring(0, 150) + '...' : content
}

const formatNumber = (num) => {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 1) return '今天'
  if (diffDays === 2) return '昨天'
  if (diffDays <= 7) return `${diffDays}天前`
  if (diffDays <= 30) return `${Math.ceil(diffDays / 7)}周前`
  if (diffDays <= 365) return `${Math.ceil(diffDays / 30)}个月前`
  return `${Math.ceil(diffDays / 365)}年前`
}

const goToStory = (storyId) => {
  router.push(`/story/${storyId}`)
}

const isLiked = (storyId) => {
  return likedStories.value.has(storyId)
}

const isUserLiked = (storyId) => {
  if (!authStore.isAuthenticated) return false
  const story = storiesStore.stories.find(s => s.id === storyId)
  // 使用后端返回的is_liked状态
  return story?.is_liked || false
}

const toggleLike = async (storyId) => {
  if (!authStore.isAuthenticated) {
    toast.warning('请先登录')
    return
  }
  
  const story = storiesStore.stories.find(s => s.id === storyId)
  if (!story) return
  
  // 乐观更新UI
  const previousLiked = story.is_liked
  const previousLikes = story.likes
  story.is_liked = !previousLiked
  story.likes = previousLiked ? previousLikes - 1 : previousLikes + 1
  
  // 添加动画效果
  const likeBtn = event.target.closest('.like-btn')
  if (likeBtn) {
    likeBtn.classList.add('pulse-animation')
    setTimeout(() => likeBtn.classList.remove('pulse-animation'), 300)
  }
  
  try {
    const result = await storiesStore.likeStory(storyId)
    if (result.success) {
      // 同步后端返回的准确数据
      story.likes = result.data.likes
      story.is_liked = result.data.is_liked
      
      if (result.data.is_liked) {
        toast.success('点赞成功！')
      } else {
        toast.info('已取消点赞')
      }
    }
  } catch (error) {
    // 失败时回滚UI状态
    story.is_liked = previousLiked
    story.likes = previousLikes
    toast.error('操作失败：' + (error.message || '请重试'))
  }
}

const shareStory = (story) => {
  if (navigator.share) {
    navigator.share({
      title: story.title,
      text: getExcerpt(story.content),
      url: `${window.location.origin}/story/${story.id}`
    })
  } else {
    navigator.clipboard.writeText(`${window.location.origin}/story/${story.id}`)
    toast.success('链接已复制到剪贴板')
  }
}

// Reset pagination when filters change
watch([searchQuery, selectedCategory, sortBy], () => {
  currentPage.value = 1
})

onMounted(async () => {
  // 加载故事数据
  try {
    await storiesStore.loadStories({
      status: 'published',
      page: 1,
      page_size: 100
    })
  } catch (error) {
    console.error('加载故事失败:', error)
  }
  
  // Animate story cards
  gsap.fromTo('.story-item',
    { opacity: 0, y: 30 },
    {
      opacity: 1,
      y: 0,
      duration: 0.6,
      stagger: 0.1,
      ease: 'power2.out'
    }
  )
})
</script>

<style scoped>
.story-library {
  padding: var(--spacing-2xl) 0;
  min-height: 100vh;
}

.library-header {
  text-align: center;
  margin-bottom: var(--spacing-3xl);
}

.page-title {
  font-size: var(--font-size-3xl);
  margin-bottom: var(--spacing-md);
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  font-size: var(--font-size-lg);
  color: var(--text-secondary);
  max-width: 600px;
  margin: 0 auto;
}

.library-controls {
  background: var(--bg-secondary);
  border-radius: var(--radius-xl);
  padding: var(--spacing-xl);
  margin-bottom: var(--spacing-2xl);
  border: 1px solid var(--border-color);
}

.search-section {
  margin-bottom: var(--spacing-lg);
}

.search-input-wrapper {
  position: relative;
  max-width: 500px;
  margin: 0 auto;
}

.search-input-wrapper svg {
  position: absolute;
  left: var(--spacing-md);
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-muted);
}

.search-input {
  width: 100%;
  padding: var(--spacing-md) var(--spacing-md) var(--spacing-md) 3rem;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  color: var(--text-primary);
  font-size: var(--font-size-base);
  transition: all var(--transition-fast);
}

.search-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.filter-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--spacing-lg);
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.filter-label {
  font-weight: 500;
  color: var(--text-primary);
  white-space: nowrap;
}

.filter-select {
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--bg-tertiary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  color: var(--text-primary);
  font-size: var(--font-size-sm);
}

.view-toggle {
  display: flex;
  background: var(--bg-tertiary);
  border-radius: var(--radius-md);
  padding: var(--spacing-xs);
}

.view-btn {
  padding: var(--spacing-sm);
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  border-radius: var(--radius-sm);
  transition: all var(--transition-fast);
}

.view-btn.active,
.view-btn:hover {
  background: var(--primary-color);
  color: white;
}

.category-tabs {
  display: flex;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-2xl);
  overflow-x: auto;
  padding-bottom: var(--spacing-sm);
}

.category-tab {
  padding: var(--spacing-sm) var(--spacing-lg);
  background: transparent;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
  white-space: nowrap;
  font-size: var(--font-size-sm);
}

.category-tab.active,
.category-tab:hover {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

.stories-container {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: var(--spacing-3xl);
  color: var(--text-secondary);
}

.empty-icon {
  margin-bottom: var(--spacing-lg);
  color: var(--text-muted);
}

.stories-grid {
  display: grid;
  gap: var(--spacing-xl);
  margin-bottom: var(--spacing-2xl);
}

.stories-grid.stories-grid {
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
}

.stories-grid.stories-list {
  grid-template-columns: 1fr;
}

.stories-list .story-card {
  display: grid;
  grid-template-columns: 1fr auto;
  gap: var(--spacing-lg);
  align-items: center;
}

.story-item {
  cursor: pointer;
}

.story-card {
  height: 100%;
  transition: all var(--transition-normal);
}

.story-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-xl);
}

.story-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--spacing-md);
}

.story-title-section {
  flex: 1;
}

.story-title {
  margin: 0 0 var(--spacing-xs) 0;
  color: var(--text-primary);
  font-size: var(--font-size-lg);
}

.story-category {
  background: var(--gradient-primary);
  color: white;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: 500;
}

.story-actions {
  display: flex;
  gap: var(--spacing-sm);
}

.action-btn {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-xs) var(--spacing-sm);
  background: transparent;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
  font-size: var(--font-size-xs);
}

.action-btn:hover:not(.disabled) {
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-primary);
}

.action-btn.pulse-animation {
  animation: pulse 0.3s ease-in-out;
}

.action-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.like-btn.liked {
  color: var(--error-color);
  border-color: var(--error-color);
  background: rgba(255, 107, 107, 0.1);
}

.like-btn.pulse-animation {
  animation: pulse 0.3s ease-in-out;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.15);
  }
  100% {
    transform: scale(1);
  }
}

.like-count {
  margin-left: 4px;
  font-weight: 500;
}

.story-content {
  margin-bottom: var(--spacing-lg);
}

.story-excerpt {
  color: var(--text-secondary);
  line-height: 1.6;
  margin: 0;
}

.story-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-color);
}

.story-author {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.story-stats {
  display: flex;
  gap: var(--spacing-md);
}

.stat {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-xs);
}

/* Pagination */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: var(--spacing-md);
  margin-top: var(--spacing-2xl);
}

.pagination-btn {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.pagination-btn:hover:not(:disabled) {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-numbers {
  display: flex;
  gap: var(--spacing-xs);
}

.pagination-number {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.pagination-number.active,
.pagination-number:hover {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

/* Mobile Styles */
@media (max-width: 768px) {
  .library-controls {
    padding: var(--spacing-lg);
  }

  .filter-section {
    flex-direction: column;
    align-items: stretch;
    gap: var(--spacing-md);
  }

  .filter-group {
    justify-content: space-between;
  }

  .stories-grid.stories-grid {
    grid-template-columns: 1fr;
  }

  .stories-list .story-card {
    grid-template-columns: 1fr;
    gap: var(--spacing-md);
  }

  .story-header {
    flex-direction: column;
    gap: var(--spacing-sm);
  }

  .story-actions {
    align-self: flex-start;
  }

  .story-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }

  .pagination {
    flex-wrap: wrap;
    gap: var(--spacing-sm);
  }

  .pagination-numbers {
    order: -1;
  }
}
</style>
